package nccloud.mob.riart.message.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import itf.approvecenter.util.DataExchangeBean;
import nc.itf.uap.pf.IWorkflowMachine;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.pf.workflow.IPFActionName;
import nc.vo.pub.workflownote.WorkflownoteVO;
import nc.vo.wfengine.definition.WorkflowTypeEnum;
import nccloud.base.exception.ExceptionUtils;
import nccloud.framework.mob.action.itf.IMobileAction;
import nccloud.framework.mob.container.IMobRequest;
import nccloud.framework.service.ServiceLocator;
import nccloud.itf.uap.pf.IApproveBusiHandler;
import nccloud.itf.uap.pf.NCCWorkFlowService;
import nccloud.putitf.riart.billtype.IBilltypeService;
import nccloud.utils.mobile_riart.MessageLogger;
import nccloud.web.workflow.approvalcenter.action.ApproveOrSignalActionUtil;
import nccloud.web.workflow.approvalcenter.action.NCCFlowInteractiveConstant;
import nccloud.web.workflow.approve.util.NCCFlowUtils;
import nccloud.web.workflow.approve.util.NCCMsgContext;

public class UnApproveAction implements IMobileAction {
	Set<String> busiexceptionCodeSet = new HashSet<String>();

	@Override
	public Object doAction(IMobRequest request) {
		DataExchangeBean bean = new DataExchangeBean();
		bean.setCode(NCCFlowInteractiveConstant.SUCCESS);
		String billType = "";
		String billId = "";
		String pk_checkflow = "";

		NCCMsgContext nccMsg = new NCCMsgContext(request.read());

		Map<String, Object> msgInfoMap = nccMsg.getMsgINfoContext();

		// 验证传过来的参数不能为空、在之后可以使用
		String[] flowParameterArray = { NCCFlowInteractiveConstant.BILL_TYPE,
				NCCFlowInteractiveConstant.BILL_ID,
				NCCFlowInteractiveConstant.CHECK_FLOW };

		if (NCCFlowUtils.isFlowParameterArrayNull(flowParameterArray,
				msgInfoMap)) {

			return NCCFlowUtils
					.exchangeDataMsg(
							bean,
							NCCFlowInteractiveConstant.ERROR,
							nc.vo.ml.NCLangRes4VoTransl.getNCLangRes()
									.getStrByID("0020nccloud_0",
											"0ncc0020001-0428")/* @res 流程参数为空 */);

		}
		// 构造所需参数
		billType = msgInfoMap.get(NCCFlowInteractiveConstant.BILL_TYPE)
				.toString();
		billId = msgInfoMap.get(NCCFlowInteractiveConstant.BILL_ID).toString();
		pk_checkflow = msgInfoMap.get(NCCFlowInteractiveConstant.CHECK_FLOW)
				.toString();

		NCCFlowUtils.checkIsExistMessage(billType, billId);

		NCCWorkFlowService nccWorkFlowService = (NCCWorkFlowService) ServiceLocator
				.find(NCCWorkFlowService.class);
		IWorkflowMachine machine = (IWorkflowMachine) ServiceLocator
				.find(IWorkflowMachine.class);
		// billType单据类型、单据id、工作项的对应的pk

		IBilltypeService billTypeServiceImpl = ServiceLocator
				.find(IBilltypeService.class);

		AggregatedValueObject billvo = null;

		WorkflownoteVO note = null;
		try {

			note = nccWorkFlowService.checkWorkflowActionsByActionType(
					billType, billId, pk_checkflow, IPFActionName.UNAPPROVE);
			billvo = nccWorkFlowService.mobileAppUtilForQueryBillEntity(
					billType, billId);

		} catch (BusinessException e) {
			ExceptionUtils.wrapException(e);

		}

		// 取消审批前的检查类
		String billtype2RegistClass = "";

		String billType_c;
		IApproveBusiHandler approveBusiAction = null;

		try {
			billType_c = billTypeServiceImpl.getRealBilltype(billType)
					.getPk_billtypecode();
			billtype2RegistClass = billTypeServiceImpl
					.getBeforeApproveCheckClass(billType_c);
			if (!"".equals(billtype2RegistClass)
					&& billtype2RegistClass != null) {

				Class clazz = Class.forName(billtype2RegistClass);

				approveBusiAction = (IApproveBusiHandler) clazz.newInstance();
				if ((nccloud.pubitf.platform.approve.AbstractApproveBusiHandlerImpl.class)
						.isAssignableFrom(approveBusiAction.getClass())) {
					nccloud.pubitf.platform.approve.AbstractApproveBusiHandlerImpl ob = (nccloud.pubitf.platform.approve.AbstractApproveBusiHandlerImpl) approveBusiAction;
					DataExchangeBean beanresult = ob.unProcessFlow(billType,
							billId, billvo, null);
					if (beanresult != null
							&& beanresult.getCode() != null
							&& (!NCCFlowInteractiveConstant.SUCCESS
									.equals(beanresult.getCode()))) {
						return (JSONObject) JSONObject.toJSON(beanresult);
					}

				}
			}
		} catch (Exception e1) {
			MessageLogger.error("第三方调用移动端审批通过接口失败【nccloud.mob.riart.message.actions.UnApproveAction】，"
					+ "失败原因【"+e1.getMessage()+"】...........");
			// TODO Auto-generated catch block
			ExceptionUtils.wrapException(e1);
		}

		// 前台的业务编码、并将该编码信息保放到环境变量中、现在放的为String
		String paramBusiCodes = null;
		if (msgInfoMap.get(NCCFlowInteractiveConstant.SKIP_CODES) != null
				&& !"[]".equals(msgInfoMap.get(
						NCCFlowInteractiveConstant.SKIP_CODES).toString())) {

			paramBusiCodes = msgInfoMap
					.get(NCCFlowInteractiveConstant.SKIP_CODES)
					.toString()
					.substring(
							1,
							msgInfoMap
									.get(NCCFlowInteractiveConstant.SKIP_CODES)
									.toString().length() - 1).replace("\"", "");
		}

		// 运行参数 放到map中方便判断是否为空（直接放入参数名称即可）
		List<Map<String, Object>> paraMapList = new ArrayList<Map<String, Object>>();
		Map paraMap = new HashMap();
		paraMap.put(NCCFlowInteractiveConstant.NCCFlOW_PARAMTER,
				NCCFlowInteractiveConstant.NCCLOUD);

		if (paramBusiCodes != null) {
			paraMap.put(NCCFlowInteractiveConstant.NCC_BUSICODES,
					paramBusiCodes);
		}
		paraMapList.add(paraMap);

		try {
			// FIXME: 加入进度条

			// 进行审批流的判断
			if (WorkflowTypeEnum.fromIntValue(note.getWorkflow_type()).equals(
					WorkflowTypeEnum.Approveflow)
					|| WorkflowTypeEnum.fromIntValue(note.getWorkflow_type())
							.equals(WorkflowTypeEnum.SubApproveflow)) {

				bean = ApproveOrSignalActionUtil.processAction(
						IPFActionName.UNAPPROVE, billType, note, billvo,
						paraMapList, null, billtype2RegistClass);

			} else {
				bean = ApproveOrSignalActionUtil.processAction(
						IPFActionName.ROLLBACK, billType, note, billvo,
						paraMapList, null, billtype2RegistClass);
			}

		} catch (Exception ex) {
			MessageLogger.error("第三方调用移动端审批通过接口失败【nccloud.mob.riart.message.actions.UnApproveAction】，"
					+ "失败原因【"+ex.getMessage()+"】...........");
			ExceptionUtils.wrapException(ex);

		}
		return (JSONObject)JSONObject.toJSON(bean);
	}
}
